<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Authenticate extends MY_JSON {

	public function __construct()
	{
		parent::__construct();
	}
	
	public function index()
	{
		$this->load->view('welcome_message');
	}
	
	public function Register()
	{
		$post_Email = $this->input->post('email');
		$post_Password = $this->input->post('password');
		$post_Name = $this->input->post('name');

		$array = $this->_CreateHash($post_Password);

		$params = array('Email' => $post_Email, 'Name' => $post_Name, 'Password' => $array["hash"], 'Salt' => $array["salt"]);
		$object = new Users($post_email, $array["hash"], $array["salt"], 1);
		$this->db->insert('Users', $object);

		$this->db->from('Privileges')->where('Id', 1);
		$query = $this->db->get();
		$row = $query->first_row();

		$this->_Change_Session($post_Email, $post_name, $row['Id'], $row['Role'], TRUE);
	}

	public function Login()
	{
		$post_Email = $this->input->post('email');
		$post_Password = $this->input->post('password');

		$this->db->from('Users')->join('Privileges', 'Privileges.Id = Users.Privileges_Id')->where('Email', $post_Email);
		$query = $this->db->get();

		if($query->num_rows() > 0)
		{
			$row = $query->first_row();
			$encrypted_password = $this->_Encode($post_Password, $row['Salt']);
			if($encrypted_password == $row['Password'])
			{
				$this->_Change_Session($row['Email'], $row['Name'], $row['Id'], $row['Role'], TRUE);
			}
		}

		

		$query = $this->db->get('Users');
	}

	public function Logout()
	{
		$this->session->sess_destroy();
	}

	public function _LoggedIn()
	{
		$user = $this->session->userdata('logged_in');
		return isset($user);
	}

	public function _Auth()
	{
		$user = $this->session->userdata('logged_in');
		if(isset($user))
		{
			$array = array();
			$array["Privilege_Id"] = $this->session->userdata('privilege_id');
			$array["Privilege_Role"] = $this->session->userdata('privilege_role');
			return $array;
		}
		else
		{
			exit("Not authorized");
		}
	}

	public function _CreateHash($_password)
	{
		$salt = mcrypt_create_iv(12, MCRYPT_RAND);
		$hash = $this->_Encode($_password, $salt);

		$array = array();
		$array["salt"] = $salt;
		$array["hash"] = $hash;
		return $array;
	}

	public function _Encode($_password, $_salt)
	{
		// 123 chars
		return crypt($password, '$5$rounds=5000' . $_salt . '$');
	}

	public function _Change_Session($_email, $_name, $_privilegeid, $_privilegerole, $_loggedin)
	{
		$newdata = array(
			'email' => $_email,
			'name' => $_name,
			'privilege_id' => $_privilegeid,
			'privilege_role' => $_privilegerole,
			'logged_in' => $_loggedin
		);
		$this->session->set_userdata($newdata);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */